<template>
	<a-table ref="listRef" :rules="rules" :option="option" @subForm="subForm" @exportExecl="exportExecl" @editHandle="editHandle">
		<template #default="type">
			<el-table-column label="封面图片" width="100">
				<template #default="scope">
					<img class='img' :src="config.serverImg + scope.row.productImageList.split(',')[0]" alt="">
				</template>
			</el-table-column>
			<el-table-column label="标题"  min-width="200">
				<template #default="scope">
					<div class="line-2">{{scope.row.productName}}</div>
				</template>
			</el-table-column>
			<el-table-column label="分类" width="180">
				<template #default="scope">
					<div v-for="(v,i) in type.typelist" :key="i">
						<span v-if="scope.row.type == v.value">{{v.name}}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column prop="productPrice" sortable="custom" label="价格" width="100"> </el-table-column>
			<el-table-column prop="sort" sortable="custom" label="排序" width="80"></el-table-column>
		</template>

		<!-- 其他操作按钮 -->
		<template #but="data">
			<div>
				<a :href="config.domain+'/index/Index/product_details.html?id='+data.data.id" target="_blank">
					<el-button type="text" size="small">
						查看
					</el-button>
				</a>
			</div>
		</template>
		
		<!-- 表单 -->
		<template #form="data">
			<el-form-item label="产品名称：">
			  <el-input v-model.trim="data.form.productName" clearable placeholder="请输入"></el-input>
			</el-form-item>
			<div class="flex c5">
			  <div class="c6">
				<el-form-item label="产品价格：">
				  <el-input v-model.trim="data.form.productPrice" clearable type="number" placeholder="请输入"></el-input>
				</el-form-item>
			  </div>
			  <div class="c6">
				<el-form-item label="产品库存：">
				  <el-input v-model.trim="data.form.productStock" clearable type="number" placeholder="请输入"></el-input>
				</el-form-item>
			  </div>
			  <div class="c6">
				<el-form-item label="列表排序：">
				  <el-input v-model.trim="data.form.sort" clearable type="number" placeholder="0最小，越大越靠前"></el-input>
				</el-form-item>
			  </div>
			</div>
			<el-form-item label="商品轮播图片：">
			  <div>
			    <p class="c4">
			      第一张为产品主图,可拖动排序,建议使用比例1:1、大小不超过1M的正方形图片最多上传5张（至少1张）
			    </p>
			    <div class="c7 flex">
			      <draggable class="list-group flex" tag="transition-group" :component-data="{
			          tag: 'div',
			          type: 'transition-group',
			          name: !drag ? 'flip-list' : null,
			        }" v-model="pageData.fileList" v-bind="dragOptions" @start="drag = true" @end="drag = false"
			        item-key="v">
			        <template #item="{ element, index }">
			          <div class="c8 flex list-group-item">
			            <el-image style="width: 100%; height: 100%" :src="config.serverImg + element" fit="contain"></el-image>
			            <div class="c10" @click="pageData.fileList.splice(index, 1)">
			              删除
			            </div>
			          </div>
			        </template>
			      </draggable>
			      <div class="c8 flex" @click="
			          pickImg.show = true;
			          pickImg.name = 'img';
			        " v-if="pageData.fileList.length < 5">
			        <div class="iconfont">&#xed21;</div>
			      </div>
			    </div>
			  </div>
			</el-form-item>
		</template>
	</a-table>

	<a-img
	    v-model:show="pickImg.show" 
	    :name="pickImg.name" 
	    @img="imgSuccess">
	</a-img>

</template>

<script setup>
	import aTable from "@/components/table/index.vue"
	import publicJS from "@/hook/public.js";
    const {config,api,ElMessage} = publicJS();
	
	const option = {
		name:'商品',
		spaceValue:'local',
		showAddBut:true,
		showEditBut:true,
		showExport:true,
		showEdit:true,
		showType:true,
		showDisable:true,
		activeWidth:150,
		getUrl:'a/goods/get_list_data_a',
		delUrl:'a/goods/del_data_a',
		getEditUrl:'a/goods/get_detail_a',
	}
	
	const listRef = ref(null);
	
	//拖拽组件配置信息
	import draggable from "vuedraggable";
	const drag = false;
	const dragOptions = {
	  animation: 200,
	  group: "description",
	  disabled: false,
	  ghostClass: "ghost",
	};

	//表单校验规则
	const rules = reactive({
		type: [{ required: true, message: '请输入选择分类', trigger: 'blur' }],
		title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
	})

	// 图片选择组件
	import aImg from "@/components/a-img-local.vue";
	const pickImg = reactive({
	  show: false,
	  name: "fileList",
	});
	
	const imgSuccess = (res) => {
	  pickImg.show = false;
	  console.log(res)
	  if (res) pageData.fileList.push(res.value);
	};
	
	//页面数据
	const pageData = reactive({
	  fileList: [],
	});
	
	//获取表单数据 进行个性化页面数据处理
	const editHandle = (data)=>{
		if(data){
			pageData.fileList = data.productImageList.split(",");//逗号分割
			if (pageData.fileList.length > 1) {
			  if (pageData.fileList[pageData.fileList.length - 1] == ",") {
			    pageData.fileList.splice(pageData.fileList.length - 1, 1);
			  }
			}
		}else{
			pageData.fileList = [];
			let form = [
				{k:'productPrice',v:''},
				{k:'productStock',v:''},
				{k:'sort',v:''},
				{k:'type',v:1},
			]
			form.forEach(data => {
				listRef.value.editForm.form[data.k] = data.v;
			})
		}
	}
	
	//提交表单
	const subForm = (data)=>{
		listRef.value.ruleFormRef.validate((valid, fields) => {
			if (valid) {
				if(!pageData.fileList.length)return ElMessage.error('请选择上传商品图片')
				if(!data?.content)return ElMessage.error('请输入详细内容')
				let url = "a/goods/add_data_a";
				if (data?.id) url = "a/goods/updata_a"
				for(let i in listRef.value.pageData.typeList){
					if(listRef.value.pageData.typeList[i].id == data.type){
						data.type = listRef.value.pageData.typeList[i].value;
						break;
					}
				}
				data.productImage = pageData.fileList[0];
				data.productImageList = pageData.fileList.join(",");//数组逗号链接 转成 字符串数据
				if(!data?.sort)data.sort = 0;
				api.post(url, data).then(r => {
					listRef.value.searchFun()
				})
			} else {
				console.log('error submit!', fields)
			}
		})
	}

	//导出数据 表格处理
	import execl from "@/utils/execl.js"
	const exportExecl = (data)=>{
		const column = [
			{
				title: '产品图片',
				key: 'productImage',
				type: 'image',
				width: "100",
				height: "100",
			},
			{
				title: '产品名称',
				key: 'productName',
				type: 'text',
			}
		]
		let datas = data.map(r=>{
			return {
				productImage:config.serverImg + r.productImageList.split(',')[0],
				productName:r.productName
			}
		})
		execl(column,datas,'产品')
	}
</script>

<style scoped lang="scss">
.img{width: 40px;}

  .c5 {
    align-items: flex-start;
  }

  .c6 {
    flex: 1;
    margin-right: 50px;
  }
  
  .c8 {
    margin-right: 10px;
    width: 150px;
    height: 150px;
    position: relative;
    border-radius: 10px;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    border: 1px dashed #d9d9d9;
  }
  
  .c8:hover {
    border-color: var(--el-color-primary);
    cursor: pointer;
  }
  
  .c8:hover .c10 {
    opacity: 1;
  }
  
  .c8 img {
    width: 100%;
    height: 100%;
    display: block;
  }
  
  .c9 {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .c10 {
    position: absolute;
    right: 0;
    bottom: 0;
    cursor: pointer;
    width: 100%;
    background: var(--el-color-primary);
    opacity: 0;
    transition: 0.3s;
    text-align: center;
    color: #fff;
    line-height: 30px;
  }
</style>